//
// Created by dreamli on 2025/11/8.
//

#include <stdio.h>
#include <string.h>
#include <time.h>
#include "sqlite3.h"
#include "database.h"
#include "order_food_control.h"


//添加数据
int order_food_add(foods_order * orders){
    char sql[256];
    sprintf(sql,"insert into order_food(user_id,foods_id,order_time,status,quety) values(%d,%d,'%s','%s',%d)",
            orders->user_id,orders->foods_id,orders->order_time,orders->status,orders->quety);
    char * errmsg;
    int rc = sqlite3_exec(db,sql,NULL,NULL,&errmsg);
    if(rc!=SQLITE_OK){
        fprintf(stderr,"订单添加出错了:%s\n",errmsg);
        sqlite3_free(errmsg);
        return -1;
    }
    printf("订单添加成功!\n");
    return 0;
}

//修改数据
int order_food_update(foods_order * orders){
    char * errmsg;
    char sql[234];
    sprintf(sql,"update order_food set status='%d' where order_id=%d",orders->order_id);
    int rs= sqlite3_exec(db,sql,NULL,NULL,&errmsg);
    if(rs!=SQLITE_OK){
        fprintf(stderr,"订单信息修改失败：%s",errmsg);
        sqlite3_free(errmsg);
        return -1;
    }
    printf("订单信息修改成功了！\n");
    return 0;
}
//删除订单信息
int order_food_delete(int order_id){
    char sql[234];
    char * errmsg;
    sprintf(sql,"delect from order_food where order_id=%d ",order_id);
    int sc= sqlite3_exec(db,sql,NULL,NULL,&errmsg);
    if(sc!=SQLITE_OK){
        fprintf(stderr,"订单信息删除失败：%s",errmsg);
        sqlite3_free(errmsg);
        return -1;
    }
    printf("订单信息删除成功了!\n");
    return 0;
}


int foods_category_callback(void *data,int argc,char **argv,char **arg_col_name){
    (*(int *)data)++;
    static int row=0;
    if(row==0){
        for(int i=0;i<argc;i++){
            printf("|%s ",arg_col_name[i]);
        }
        row=1;
        printf("\n");
        printf("-------------------------------------\n");
    }
    for(int i=0;i<argc;i++ ){
        printf("|%s ",argv[i]);
    }
    printf("|\n");
    return 0;
}

int order_food_query(){
    char * errmsg;
    int rowcount=0;
    char * sql="select order_id,user_id,foods_id,order_time,status,quety from order_food";
    int rc= sqlite3_exec(db,sql,foods_category_callback,&rowcount,&errmsg);
    if(rc!=SQLITE_OK){
        fprintf(stderr,"订单查询失败：%s",errmsg);
        return -1;
    }
    printf("订单查询成功！\n");
    return 0;
}


//订单
// 获取当前时间字符串
void get_current_time(char *time_str) {
    time_t now;
    struct tm *tm_info;
    time(&now);
    tm_info = localtime(&now);
    strftime(time_str, 20, "%Y-%m-%d %H:%M:%S", tm_info);
}

// 获取食品价格
float get_food_price(int foods_id) {
    float price = 0.0;
    char sql[256];
    sqlite3_stmt *stmt;

    sprintf(sql, "SELECT price FROM foods_message WHERE foods_id = %d;", foods_id);

    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
        fprintf(stderr, "获取食品价格失败: %s\n", sqlite3_errmsg(db));
        return 0.0;
    }

    if (sqlite3_step(stmt) == SQLITE_ROW) {
        price = sqlite3_column_double(stmt, 0);
    } else {
        fprintf(stderr, "未找到食品ID: %d\n", foods_id);
    }

    sqlite3_finalize(stmt);
    return price;
}

// 直接创建订单
int create_order_directly(int user_id, int foods_id, int quantity) {
    // 检查库存
    char sql[256];
    sqlite3_stmt *stmt;
    int current_qty = 0;

    sprintf(sql, "SELECT current_quantity FROM create_stock WHERE food_id = %d;", foods_id);
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
        fprintf(stderr, "查询库存失败: %s\n", sqlite3_errmsg(db));
        return -1;
    }

    if (sqlite3_step(stmt) == SQLITE_ROW) {
        current_qty = sqlite3_column_int(stmt, 0);
    } else {
        fprintf(stderr, "未找到食品库存信息: %d\n", foods_id);
        sqlite3_finalize(stmt);
        return -1;
    }
    sqlite3_finalize(stmt);

    if (current_qty < quantity) {
        fprintf(stderr, "库存不足! 当前库存: %d, 所需数量: %d\n", current_qty, quantity);
        return -1;
    }

    // 创建订单
    foods_order order;
    order.user_id = user_id;
    order.foods_id = foods_id;
    order.quety = quantity;
    get_current_time(order.order_time);
    strcpy(order.status, "未结算");
    order.total_price = get_food_price(foods_id) * quantity;

    // 插入订单记录
    sprintf(sql, "INSERT INTO order_food(user_id, foods_id, order_time, status, quety) VALUES(%d ,%d, %d,'%s', '%s', %d);",
       order.user_id, order.foods_id, order.order_time, order.status, order.quety);

    char *errmsg = NULL;
    int rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "创建订单失败: %s\n", errmsg);
        sqlite3_free(errmsg);
        return -1;
    }

    // 获取生成的订单ID
    int order_id = sqlite3_last_insert_rowid(db);
    printf("订单创建成功! 订单ID: %d, 金额: %.2f元\n", order_id, order.total_price);

    return order_id;
}

// 结算订单
int calculate_order(int order_id) {
    // 查询订单信息
    char sql[256];
    sqlite3_stmt *stmt;
    int foods_id, quantity, user_id;

    sprintf(sql, "SELECT user_id, foods_id, quety, status FROM order_food WHERE order_id = %d;", order_id);
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
        fprintf(stderr, "查询订单失败: %s\n", sqlite3_errmsg(db));
        return -1;
    }

    if (sqlite3_step(stmt) != SQLITE_ROW) {
        fprintf(stderr, "未找到订单ID: %d\n", order_id);
        sqlite3_finalize(stmt);
        return -1;
    }

    user_id = sqlite3_column_int(stmt, 0);
    foods_id = sqlite3_column_int(stmt, 1);
    quantity = sqlite3_column_int(stmt, 2);
    const char *status = (const char *)sqlite3_column_text(stmt, 3);

    // 检查订单状态
    if (strcmp(status, "已结算") == 0) {
        fprintf(stderr, "订单ID: %d 已经结算过了\n", order_id);
        sqlite3_finalize(stmt);
        return -1;
    }
    sqlite3_finalize(stmt);

    // 更新订单状态
    char *errmsg = NULL;
    sprintf(sql, "UPDATE order_food SET status = '已结算' WHERE order_id = %d;", order_id);
    int rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "更新订单状态失败: %s\n", errmsg);
        sqlite3_free(errmsg);
        return -1;
    }

    // 减少库存
    sprintf(sql, "UPDATE create_stock SET current_quantity = current_quantity - %d WHERE food_id = %d;",
            quantity, foods_id);
    rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "更新库存失败: %s\n", errmsg);
        sqlite3_free(errmsg);
        return -1;
    }

    // 计算总价并显示
    float price = get_food_price(foods_id);
    float total = price * quantity;
    printf("订单结算成功! 订单ID: %d, 总金额: %.2f元\n", order_id, total);
    return 0;
}
TempOrderList temp_order = {.count = 0, .total_price = 0.0};

// 初始化临时订单（清空历史数据）
void init_temp_order() {
    temp_order.count = 0;
    temp_order.total_price = 0.0;
    memset(temp_order.items, 0, sizeof(temp_order.items));
    printf("已清空点单列表，可重新点单\n");
}

// 获取菜品名称（新增辅助函数）
const char* get_food_name(int foods_id) {
    static char name[50] = "未知菜品";
    char sql[256];
    sqlite3_stmt *stmt;

    sprintf(sql, "SELECT foods_name FROM foods_message WHERE foods_id = %d;", foods_id);
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
        fprintf(stderr, "获取菜品名称失败: %s\n", sqlite3_errmsg(db));
        return name;
    }

    if (sqlite3_step(stmt) == SQLITE_ROW) {
        strcpy(name, (const char*)sqlite3_column_text(stmt, 0));
    }
    sqlite3_finalize(stmt);
    return name;
}

// 添加菜品到临时订单（核心：支持连续点单）
int add_to_temp_order(int foods_id, int quantity) {
    // 检查是否超过最大点单数量
    if (temp_order.count >= 10) {
        printf("最多只能点10种菜品，请先结算\n");
        return -1;
    }

    // 检查库存（复用原有逻辑）
    int current_qty = 0;
    char sql[256];
    sqlite3_stmt *stmt;
    sprintf(sql, "SELECT current_quantity FROM create_stock WHERE food_id = %d;", foods_id);
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
        fprintf(stderr, "查询库存失败: %s\n", sqlite3_errmsg(db));
        return -1;
    }
    if (sqlite3_step(stmt) == SQLITE_ROW) {
        current_qty = sqlite3_column_int(stmt, 0);
    } else {
        fprintf(stderr, "未找到菜品库存信息\n");
        sqlite3_finalize(stmt);
        return -1;
    }
    sqlite3_finalize(stmt);

    if (current_qty < quantity) {
        fprintf(stderr, "库存不足! 当前库存: %d, 所需数量: %d\n", current_qty, quantity);
        return -1;
    }

    // 获取菜品单价和名称
    float price = get_food_price(foods_id);
    const char* name = get_food_name(foods_id);

    // 添加到临时订单
    TempOrderItem *item = &temp_order.items[temp_order.count];
    item->foods_id = foods_id;
    strcpy(item->foods_name, name);
    item->quantity = quantity;
    item->price = price;
    item->total = price * quantity;

    // 累计总价和数量
    temp_order.count++;
    temp_order.total_price += item->total;

    printf("已添加【%s】×%d，单价: %.2f元，小计: %.2f元\n",
           name, quantity, price, item->total);
    return 0;
}

// 确认订单并结算（显示总价，生成正式订单）
int confirm_and_pay(int user_id) {
    if (temp_order.count == 0) {
        printf("您还没有点任何菜品\n");
        return -1;
    }

    // 显示订单详情和总价
    printf("\n===== 订单确认 =====\n");
    printf("序号 | 菜品名称 | 数量 | 单价 | 小计\n");
    printf("----------------------------------------\n");
    for (int i = 0; i < temp_order.count; i++) {
        TempOrderItem *item = &temp_order.items[i];
        printf("%d.   %s   ×%d   %.2f元   %.2f元\n",
               i+1, item->foods_name, item->quantity,
               item->price, item->total);
    }
    printf("----------------------------------------\n");
    printf("订单总价: %.2f元\n", temp_order.total_price);

    // 询问是否确认结算
    printf("是否确认结算？(1.确认 2.取消): ");
    int choice;
    scanf("%d", &choice);
    if (choice != 1) {
        printf("已取消结算，可继续点单\n");
        return -1;
    }

    // 生成正式订单（一条记录对应一个菜品，方便后续管理）
    char time_str[20];
    get_current_time(time_str);
    char *errmsg = NULL;
    int rc;

    // 开启事务，确保所有菜品同时结算成功
    sqlite3_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &errmsg);

    for (int i = 0; i < temp_order.count; i++) {
        TempOrderItem *item = &temp_order.items[i];
        // 插入订单记录
        char sql[512];
        sprintf(sql,
                "INSERT INTO order_food(user_id, foods_id, order_time, status, quety, total_price) "
                "VALUES(%d, %d, '%s', '已结算', %d, %.2f);",
                user_id, item->foods_id, time_str, item->quantity, item->total);
        rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
        if (rc != SQLITE_OK) {
            fprintf(stderr, "创建订单失败: %s\n", errmsg);
            sqlite3_exec(db, "ROLLBACK;", NULL, NULL, NULL); // 回滚事务
            sqlite3_free(errmsg);
            return -1;
        }

        // 减少库存
        sprintf(sql, "UPDATE create_stock SET current_quantity = current_quantity - %d "
                     "WHERE food_id = %d;", item->quantity, item->foods_id);
        rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
        if (rc != SQLITE_OK) {
            fprintf(stderr, "更新库存失败: %s\n", errmsg);
            sqlite3_exec(db, "ROLLBACK;", NULL, NULL, NULL); // 回滚事务
            sqlite3_free(errmsg);
            return -1;
        }
    }

    // 所有菜品处理完成，提交事务
    sqlite3_exec(db, "COMMIT;", NULL, NULL, &errmsg);
    printf("\n===== 结算成功！=====\n");
    printf("订单总金额: %.2f元，感谢您的光临\n", temp_order.total_price);

    // 清空临时订单，准备下次点单
    init_temp_order();
    return 0;
}

